package webbandidong.auth;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

public abstract class AuthAdminSimpleFormController extends SimpleFormController {

    @Override
    protected ModelAndView onSubmit(
            HttpServletRequest request,
            HttpServletResponse response,
            Object command,
            BindException errors) throws Exception {
        
        if (!CheckAuth.checkAdminAuth(request, response)) {
            return null;
        }
        else {
            ModelAndView mv = onAuthSubmit(request, response, command, errors);
            return mv;
        }
    }

    /**
     * Override phuong thuc trong AbstractFormController la super cua
     * SimpleFormController
     */
    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request, 
            HttpServletResponse response) throws Exception {
        // Neu la POST request thi vao phuong thuc onSubmit - Kiem tra
        // authorization trong onSubmit
        // Cung co the kiem tra luon o day cung duoc
        if (isFormSubmission(request)) {
            return super.handleRequestInternal(request, response);
        }
        // Neu la GET kiem tra authorization
        // Neu OK thi show form
        // Neu khong thi redirect den trang dang nhap
        else {
            if (!CheckAuth.checkAdminAuth(request, response)) {
                return null;
            }
            return showNewForm(request, response);
        }
    }

    public abstract ModelAndView onAuthSubmit(HttpServletRequest request,
            HttpServletResponse response,
            Object command,
            BindException errors) throws Exception;
}
